using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace CastleSample.Entity
{
    [Serializable]
    public class UserContext
    {
        public UserContext()
        {
            m_ClientInstanceId = m_StaticClientInstanceId;
        }

        private static UserContext m_Current;

        public static UserContext Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new UserContext();
                    m_Current.AuthenticationToken = "";
                    m_Current.UserName = "";
                    m_Current.LoggedIn = false;
                }
                return m_Current;
            }
            set
            {
                if (value == null)
                {
                    m_Current = new UserContext();
                    m_Current.AuthenticationToken = "";
                    m_Current.UserName = "";
                    m_Current.LoggedIn = false;
                }
                else
                {
                    m_Current = value;
                }
            }
        }

        private static string m_StaticClientInstanceId = Guid.NewGuid().ToString();

        private string m_ClientInstanceId;

        public string ClientInstanceId
        {
            get { return m_ClientInstanceId; }
        }

        private string m_AuthenticationToken = "";

        public string AuthenticationToken
        {
            get { return m_AuthenticationToken; }
            set { m_AuthenticationToken = value; }
        }

        private string m_UserName = "";

        public string UserName
        {
            get { return m_UserName; }
            set { m_UserName = value; }
        }

        private bool m_OnlineMode = false;

        public bool OnlineMode
        {
            get { return m_OnlineMode; }
            set { m_OnlineMode = value; }
        }

        private bool m_LoggedIn = false;

        public bool LoggedIn
        {
            get { return m_LoggedIn; }
            set { m_LoggedIn = value; }
        }

        public void Reset()
        {
            UserName = "";
            AuthenticationToken = "";
            LoggedIn = false;
            OnlineMode = false;
        }

        public override string ToString()
        {
            XmlSerializer xs = new XmlSerializer(GetType());
            StringBuilder sb = new StringBuilder();
            TextWriter tw = new StringWriter(sb);
            xs.Serialize(tw, this);
            tw.Flush();
            string str = sb.ToString();
            tw.Close();
            return str;
        }
    }
}